package com.digitalchina.lxnsy.wxapi;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.alipay.sdk.app.PayTask;
import com.apkfuns.logutils.LogUtils;
import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.activity.farmVideo.TradeSuccessVideoActivity;
import com.digitalchina.lxnsy.activity.old.MyOrderListActivity;
import com.digitalchina.lxnsy.activity.old.MyShareBuyOrderListActivity;
import com.digitalchina.lxnsy.activity.old.OrderDetailsActivity;
import com.digitalchina.lxnsy.activity.old.SelectProductionActivityV2;
import com.digitalchina.lxnsy.activity.old.SetPayPasswordOneActivity;
import com.digitalchina.lxnsy.activity.old.ShareOrderDetailsActivity;
import com.digitalchina.lxnsy.activity.old.TradeSuccessActivity;
import com.digitalchina.lxnsy.alipay.ALiKeys;
import com.digitalchina.lxnsy.alipay.ALiPay;
import com.digitalchina.lxnsy.alipay.PayResult;
import com.digitalchina.lxnsy.api.BusinessFarmSystem;
import com.digitalchina.lxnsy.api.BusinessPayPassword;
import com.digitalchina.lxnsy.api.BusinessPlan;
import com.digitalchina.lxnsy.base.BaseActivity;
import com.digitalchina.lxnsy.constant.Constant;
import com.digitalchina.lxnsy.constant.MSG;
import com.digitalchina.lxnsy.constant.URL;
import com.digitalchina.lxnsy.entity.MyOrderListVO;
import com.digitalchina.lxnsy.entity.OrderDisplayVO;
import com.digitalchina.lxnsy.entity.PayVO;
import com.digitalchina.lxnsy.toolkit.ActivityTaskManager;
import com.digitalchina.lxnsy.toolkit.CustomDialog;
import com.digitalchina.lxnsy.toolkit.EncryptUtil;
import com.digitalchina.lxnsy.toolkit.FastJsonUtil;
import com.digitalchina.lxnsy.toolkit.GotoUtil;
import com.digitalchina.lxnsy.toolkit.OkHttpUtil;
import com.digitalchina.lxnsy.xml.UserXML;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.lzy.okhttputils.model.HttpParams;
import com.mock.alipay.Callback;
import com.mock.alipay.PasswordKeypad;
import com.tencent.mm.sdk.constants.ConstantsAPI;
import com.tencent.mm.sdk.modelbase.BaseReq;
import com.tencent.mm.sdk.modelbase.BaseResp;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import org.jdom.JDOMException;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Request;
import okhttp3.Response;

/**
 * ================================================
 * 项目名称：BigData
 * 类描述：收银台
 * 包名：com.digitalchina.bigdata.activity
 * 创建人：白彦东
 * 创建时间：2016/8/13 12:54
 * 修改备注：类名/包名不能修改
 * ================================================
 */
public class WXPayEntryActivity extends BaseActivity implements IWXAPIEventHandler {


    @Bind(R.id.activity_checkout_counter_tv_money_need_pay)
    TextView activityCheckoutCounterTvMoneyNeedPay;//支付金额
    @Bind(R.id.activity_checkout_counter_ck_alipay)
    CheckBox activityCheckoutCounterCkAlipay;//支付宝支付
    @Bind(R.id.activity_checkout_counter_btn_confirm_pay)
    Button activityCheckoutCounterBtnConfirmPay;//确认支付
    @Bind(R.id.activity_checkout_counter_alipay)
    RelativeLayout activityCheckoutCounterAlipay;//支付宝支付布局
    @Bind(R.id.activity_checkout_counter_ck_wxpay)
    CheckBox activityCheckoutCounterCkWxpay;
    @Bind(R.id.cb_qb)
    CheckBox cbQb;
    @Bind(R.id.layout_nb)
    RelativeLayout layoutNb;

    private int onlinepayType; // 支付类型 支付宝or微信
    //    private String notifyType; // 支付宝/微信回调
    private String payType; // 线上or线下
    private OrderDisplayVO orderDisplayVO;
    private MyOrderListVO myOrderListVO;
    private String orderNo;

    private static final int SDK_PAY_FLAG = 1;
    private IWXAPI api; // 微信支付
    private int msgWhat;

    // 支付类型 支付宝=0 微信=1 电子钱包=2
    private static final int PAY_TYPE_ALI = 0;
    private static final int PAY_TYPE_WX = 1;
    private static final int PAY_TYPE_QB = 2;
    // 异步回调接口
    private static final String NOTIFY_URL_ALI = URL.SERVER + "fsp/payment/instantNotifyDispose";
    private static final String NOTIFY_URL_WX = URL.SERVER + "agsrv/payresult/payResult";

    // 测试数据
    private String price = ""; // 付款价格

    private int type;

    private String aliPayUrl = "";
    private String wxPayUrl = "";
    private String goodsName = "";

    private String expertId = ""; //专家ID 咨询付费使用

    private boolean mHavePayPassword = false; // 是否设置过支付密码
    private PasswordKeypad mKeypad;


    @Override
    public void setLayout() {
        setContentLayout(R.layout.activity_checkout_counter);
        setTitle("收银台");
    }

    @Override
    public void initMember() {

        // 默认选中微信支付
        onlinepayType = PAY_TYPE_WX;
        payType = Constant.PAYMENT_TYPE_ON_LINE;
        activityCheckoutCounterCkWxpay.setChecked(true);

        mKeypad = new PasswordKeypad();
        mKeypad.setPasswordCount(6);

        if (getIntent().hasExtra("payVO")) {//支付实体
            PayVO payVO = (PayVO) getIntent().getSerializableExtra("payVO");
            type = payVO.getType();
            price = payVO.getPrice();
            orderNo = payVO.getOrderNO();
            goodsName = payVO.getGoodsName();
            activityCheckoutCounterTvMoneyNeedPay.setText(price);

            // 1 买卖书订单  2 共享订单  3 标准化种植 4 专家咨询
            switch (type) {
                case 1:
                    aliPayUrl = ALiKeys.ALIPAY_NOTIFY_URL;
                    wxPayUrl = WXKeys.WX_NOTIFY_URL;
                    break;
                case 2:
                    aliPayUrl = ALiKeys.ALIPAY_NOTIFY_URL;
                    wxPayUrl = WXKeys.WX_NOTIFY_URL;
                    break;
                case 3:
                    aliPayUrl = ALiKeys.ALIPAY_NOTIFY_URL2;
                    wxPayUrl = WXKeys.WX_NOTIFY_URL2;
                    break;
                case 4:
                    aliPayUrl = ALiKeys.ALIPAY_NOTIFY_URL3;
                    wxPayUrl = WXKeys.WX_NOTIFY_URL3;
                    expertId = payVO.getOrderNO();
                    break;
                case 5:
                    aliPayUrl = ALiKeys.ALIPAY_NOTIFY_URL4;
                    wxPayUrl = WXKeys.WX_NOTIFY_URL4;
                    layoutNb.setVisibility(View.VISIBLE);
                    break;
            }

        }

    }

    @Override
    public void addListener() {
        // 微信
        activityCheckoutCounterCkWxpay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onlinepayType = PAY_TYPE_WX;
                activityCheckoutCounterCkWxpay.setChecked(true);
                activityCheckoutCounterCkAlipay.setChecked(false);
                cbQb.setChecked(false);
            }
        });
        // 支付宝
        activityCheckoutCounterCkAlipay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onlinepayType = PAY_TYPE_ALI;
                activityCheckoutCounterCkWxpay.setChecked(false);
                activityCheckoutCounterCkAlipay.setChecked(true);
                cbQb.setChecked(false);
            }
        });
        // 电子钱包
        cbQb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onlinepayType = PAY_TYPE_QB;
                activityCheckoutCounterCkWxpay.setChecked(false);
                activityCheckoutCounterCkAlipay.setChecked(false);
                cbQb.setChecked(true);
            }
        });

        //密码键盘
        mKeypad.setCallback(new Callback() {
            @Override
            public void onForgetPassword() {
                GotoUtil.gotoActivity(activity, SetPayPasswordOneActivity.class, true, "type", 1);
            }

            @Override
            public void onInputCompleted(CharSequence password) {
                HttpParams params = new HttpParams();

                params.put("userAccId", UserXML.getUserId(activity));
                params.put("paymentPwd", EncryptUtil.SHA1(password.toString()));
                params.put("orderNo", orderNo);
                params.put("amount", price);


                OkHttpUtil.post(activity, URL.URL_VIDEO_BUY, "", params, mHandler,
                        MSG_S_1, MSG_F_1);
            }

            @Override
            public void onPasswordCorrectly() {
                mKeypad.dismiss();
            }

            @Override
            public void onCancel() {
                //todo:做一些埋点类的需求
            }
        });
    }

    @Override
    public void setHandler() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                dismissDialog();
                msgWhat = msg.what;

                switch (msg.what) {
                    case MSG.MSG_BUYER_ORDER_DETAIL_SUCCESS://订单详情
                        callBack(msg.obj);
                        break;
                    case MSG.MSG_BUYER_ORDER_DETAIL_FIELD:
                        showToast(msg.obj.toString());
                        break;
                    case SDK_PAY_FLAG: // 支付宝
                        callBack(msg.obj);
                        break;
                    case MSG.MSG_UPDATE_ORDER_SUCCESS://更新支付类型成功

                        switch (onlinepayType) {
                            case PAY_TYPE_ALI:
                                alipay();// 支付宝支付
                                break;
                            case PAY_TYPE_WX:
                                wxpay(); // 微信支付
                                break;
                        }
                        break;

                    case MSG_S_0:
                        orderNo = FastJsonUtil.getString(msg.obj.toString(), "orderNo");
                        switch (onlinepayType) {
                            case PAY_TYPE_ALI:
                                alipay();// 支付宝支付
                                break;
                            case PAY_TYPE_WX:
                                wxpay(); // 微信支付
                                break;
                        }
                        break;
                    case MSG_F_0:
                        showToast(msg.obj.toString());
                        break;
                    case MSG.MSG_HAVE_PAY_PASSWORD_SUCCESS: // 查询用户是否设置支付密码
                        String havePayPassword = FastJsonUtil.getString(msg.obj.toString(), "havePayPassword");

                        if (havePayPassword.equals("0")) {
                            mHavePayPassword = false;
                            new MaterialDialog.Builder(activity)
                                    .title("提示")
                                    .content("您还没有设置过提现密码，是否现在设置？")
                                    .positiveText("去设置")
                                    .negativeText("取消")
                                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                                        @Override
                                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                            GotoUtil.gotoActivity(activity, SetPayPasswordOneActivity.class, "type", 0);
                                        }
                                    })
                                    .show();
                        } else {
                            mHavePayPassword = true;
                            inputPsw();
                        }
                        break;
                    case MSG_S_1:
                        mKeypad.dismiss();
                        payVideoSuccess();
                        break;
                    case MSG_F_1:
                        mKeypad.setPasswordState(false, msg.obj.toString());
                        showToast(msg.obj.toString());
                        break;
                }
            }
        };
    }

    @Override
    public void callBack(Object object) {
        switch (msgWhat) {
            case SDK_PAY_FLAG: {

                PayResult payResult = new PayResult((String) object);

                LogUtils.e("payResult---" + payResult);
                /**
                 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                 */
                String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                String resultStatus = payResult.getResultStatus();

                LogUtils.e("resultStatus---" + resultStatus);
                // 判断resultStatus 为9000则代表支付成功
                if (TextUtils.equals(resultStatus, "9000")) {
                    // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                    Toast.makeText(WXPayEntryActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                    closeActivity();
                } else {
                    // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                    Toast.makeText(WXPayEntryActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
//                    GotoUtil.gotoActivity(WXPayEntryActivity.this, TradeFailedActivity.class, true);
                }
            }
            break;
            case MSG.MSG_BUYER_ORDER_DETAIL_SUCCESS://订单详情

                myOrderListVO = FastJsonUtil.getBean(object.toString(), "body", "orderInfo", MyOrderListVO.class);

                orderNo = myOrderListVO.getOrderNo();
                price = myOrderListVO.getTotalPriceReal();

                LogUtils.e("获取订单详情");

                switch (onlinepayType) {
                    case PAY_TYPE_ALI:
                        alipay();// 支付宝支付
                        break;
                    case PAY_TYPE_WX:
                        wxpay(); // 微信支付
                        break;
                }

                break;
        }
    }

    private void closeActivity() {
        Map<String, Object> map = new HashMap<>();

        // 1 买卖书订单  2 共享订单  3 标准化种植 4 专家咨询
        switch (type) {
            case 1:
                type1(map);
                break;
            case 2:
                type1(map);
                break;
            case 3:
                ActivityTaskManager.getInstance().closeActivity(SelectProductionActivityV2.class);
                map.put("type", type);
                map.put("productName", goodsName);
                GotoUtil.gotoActivity(WXPayEntryActivity.this, TradeSuccessActivity.class, true, "map", map);
                break;
            case 4:
                Intent i = new Intent();
                i.putExtra("orderNo", orderNo);
                setResult(RESULT_OK, i);
                finish();
                break;
            case 5:
//                map.put("type", type);
//                map.put("productName", goodsName);
                payVideoSuccess();
                break;
        }


    }

    private void type1(Map<String, Object> map) {
        if (ActivityTaskManager.getInstance().hasActivity(MyOrderListActivity.class))
            ActivityTaskManager.getInstance().closeActivity(MyOrderListActivity.class);
        if (ActivityTaskManager.getInstance().hasActivity(OrderDetailsActivity.class))
            ActivityTaskManager.getInstance().closeActivity(OrderDetailsActivity.class);
        if (ActivityTaskManager.getInstance().hasActivity(MyShareBuyOrderListActivity.class))
            ActivityTaskManager.getInstance().closeActivity(MyShareBuyOrderListActivity.class);
        if (ActivityTaskManager.getInstance().hasActivity(ShareOrderDetailsActivity.class))
            ActivityTaskManager.getInstance().closeActivity(ShareOrderDetailsActivity.class);

        map.put("type", type);
        map.put("productName", getAllItemsName());
        GotoUtil.gotoActivity(WXPayEntryActivity.this, TradeSuccessActivity.class, true, "map", map);
    }

    /**
     * 获取所有商品名称
     *
     * @return String
     */
    private String getAllItemsName() {
        String itemsName = "";
        for (int i = 0; i < myOrderListVO.getOrderItems().size(); i++) {
            itemsName += (String.format("%s、", myOrderListVO.getOrderItems().get(i).getProductName()));
        }
        if (itemsName.length() < 1)
            return "";

        return itemsName.substring(0, itemsName.length() - 1);
    }

    @Override
    public void rightOnClick() {

    }


    /**
     * 微信支付
     */
    private void wxpay() {

        if (!isWXAppInstalledAndSupported()) {
            CustomDialog.nativeDialog(this, "未检测到微信，请下载安装！");
            return;
        }

        showDialog("请稍后···");

        // 将该app注册到微信
        api = WXAPIFactory.createWXAPI(this, WXKeys.WX_APP_ID, false);
        api.registerApp(WXKeys.WX_APP_ID);


        OkHttpUtils.post(WXKeys.WX_ORDER_URL).postString(WXPay.getWeChatOrder(orderNo, new BigDecimal(price), wxPayUrl)).execute(new StringCallback() {
            @Override
            public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {
                LogUtils.e(s);

                try {
                    Map map = WXUtils.doXMLParse(s);
                    LogUtils.e(map);
                    callWXpay(map);
                } catch (JDOMException | IOException e) {
                    e.printStackTrace();
                }
            }

            private void callWXpay(Map map) {

                if (map.get("return_code").toString().equals("FAIL")) {
                    dismissDialog();
                    showToast(map.get("return_msg").toString());
                    return;
                }


                if (map.get("return_code").toString().equals("SUCCESS") && map.get("result_code").toString().equals("SUCCESS")) {


                    String timeStamp = WXUtils.getCurrentTimeMillis();

                    StringBuffer wxsb = new StringBuffer();

                    wxsb.append("appid=").append(map.get("appid").toString());
                    wxsb.append("&noncestr=").append(map.get("nonce_str").toString());
                    wxsb.append("&package=").append(WXKeys.WX_PACKAGE);
                    wxsb.append("&partnerid=").append(map.get("mch_id").toString());
                    wxsb.append("&prepayid=").append(map.get("prepay_id").toString());
                    wxsb.append("&timestamp=").append(timeStamp);
                    wxsb.append("&key=" + WXKeys.WX_API_KEY);  //微信支付商户密钥
                    LogUtils.e(wxsb);

                    //MD5签名
                    String sign = EncryptUtil.MD5(wxsb.toString()).toUpperCase();
                    LogUtils.e(sign);


                    PayReq req = new PayReq();
                    req.appId = map.get("appid").toString();
                    req.nonceStr = map.get("nonce_str").toString();
                    req.packageValue = WXKeys.WX_PACKAGE;
                    req.partnerId = map.get("mch_id").toString();
                    req.prepayId = map.get("prepay_id").toString();
                    req.sign = sign;
                    req.timeStamp = timeStamp;
                    req.extData = "app data";
                    LogUtils.e(req);
                    api.sendReq(req);
                } else {
                    dismissDialog();
                    showToast(map.get("err_code_des").toString());
                }

            }
        });

    }


    private void alipay() {

        // 订单
        String orderInfo = ALiPay.getOrderInfo(orderNo, "农科专家", price, aliPayUrl);

        // 对订单做RSA 签名
        String sign = ALiPay.sign(orderInfo);
        try {
            // 仅需对sign 做URL编码
            sign = URLEncoder.encode(sign, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        /**
         * 完整的符合支付宝参数规范的订单信息
         */
        final String payInfo = orderInfo + "&sign=\"" + sign + "\"&" + ALiPay.getSignType();

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                LogUtils.e("支付宝支付run");
                // 构造PayTask 对象
                PayTask alipay = new PayTask(WXPayEntryActivity.this);
                LogUtils.e("alipay---" + alipay);
                // 调用支付接口，获取支付结果
                String result = alipay.pay(payInfo, true);

                LogUtils.e("result---" + result);
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();


    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        api.handleIntent(intent, this);
    }


    @Override
    public void onReq(BaseReq baseReq) {

    }

    @Override
    public void onResp(BaseResp baseResp) {
        LogUtils.e("onPayFinish, errCode = " + baseResp.errCode);

        dismissDialog();

        if (baseResp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {
            if (-2 == baseResp.errCode) { // 用户取消	无需处理。发生场景：用户不支付了，点击取消，返回APP。
                showTips("微信支付结果：交易取消");
            } else if (0 == baseResp.errCode) {
                showToast("微信支付结果: 交易成功");
                closeActivity();
            } else { // errorCode:-1 错误 可能的原因：签名错误、未注册APPID、项目设置APPID不正确、注册的APPID与设置的不匹配、其他异常等。
                showTips("微信支付结果: 交易失败");
            }
        }
    }

    /**
     * 支付结果提示框
     *
     * @param msg 提示信息
     */
    private void showTips(String msg) {
        new AlertDialog.Builder(this)
                .setTitle("提示")
                .setMessage(msg)
                .show();
    }

    @OnClick(R.id.activity_checkout_counter_btn_confirm_pay)
    public void onViewClicked() {

        // 1 买卖书订单  2 共享订单  3 标准化种植 4 专家咨询
        switch (type) {
            case 1:
                BusinessFarmSystem.buyerOrderDetail(this, orderNo, mHandler);//获取订单详情(判断应付金额)
                break;
            case 2:
                BusinessFarmSystem.buyerOrderDetail(this, orderNo, mHandler);//获取订单详情(判断应付金额)
                break;
            case 3:
                BusinessPlan.updateOrder(this, orderNo, String.valueOf(onlinepayType), mHandler);
                break;
            case 4:
                generatedOrder();
                break;
            case 5:

                switch (onlinepayType) {
                    case PAY_TYPE_ALI:
                        alipay();// 支付宝支付
                        break;
                    case PAY_TYPE_WX:
                        wxpay(); // 微信支付
                        break;
                    case PAY_TYPE_QB:
                        payQb(); // 钱包支付
                        break;
                }
                break;
        }


    }

    //钱包支付
    private void payQb() {
        //设置过支付密码
        if (mHavePayPassword) {
            inputPsw();
        } else
            BusinessPayPassword.havePayPassword(this, mHandler);
    }

    //输入6位密码
    private void inputPsw() {
        mKeypad.show(getSupportFragmentManager(), "PasswordKeypad");
    }

    //支付成功
    private void payVideoSuccess() {
        go(TradeSuccessVideoActivity.class);
        finish();
    }


    private boolean isWXAppInstalledAndSupported() {
        IWXAPI msgApi = WXAPIFactory.createWXAPI(this, null);
        return msgApi.isWXAppInstalled() && msgApi.isWXAppSupportAPI();
    }

    //付费专家下单
    public void generatedOrder() {
        HttpParams params = new HttpParams();
        params.put("paymentMethod", String.valueOf(onlinepayType));
        params.put("amount", price);
        params.put("expertId", expertId);
        params.put("userAccId", UserXML.getUserId(activity));

        OkHttpUtil.post(activity, URL.URL_GENERATED_ORDER, "正在下单", params, mHandler,
                MSG_S_0, MSG_F_0);
    }


}
